package com.yami.trading.huobi.data.internal;

import com.yami.trading.bean.data.domain.Kline;
import com.yami.trading.bean.item.domain.Item;
import com.yami.trading.common.config.ThreadPoolComponent;
import com.yami.trading.huobi.hobi.HobiDataService;
import com.yami.trading.huobi.hobi.internal.FakeKlineInitService;
import com.yami.trading.service.item.ItemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class KlineInitServiceImpl implements KlineInitService {
    private static Logger logger = LoggerFactory.getLogger(KlineInitServiceImpl.class);

    @Autowired
    private KlineService klineService;
    @Autowired
    private HobiDataService hobiDataService;
    @Autowired
    private ThreadPoolComponent threadPoolComponent;
    @Autowired
    private ItemService itemService;
    @Autowired
    private CryptosKlineService cryptosKlineService;
    @Autowired
    private FakeKlineInitService fakeKlineInitService;

    @Override
    public void klineInit(String symbols) {
        logger.info("当前开始初始化币对k线图: {}", symbols);
        if (!symbols.contains(",")) {
            Item bySymbol = itemService.findBySymbol(symbols);
            if (Item.cryptos.equalsIgnoreCase(bySymbol.getType())) {
                cryptosKlineService.saveInit(symbols);
            } else if ("1".equalsIgnoreCase(bySymbol.getFake())) {
                fakeKlineInitService.saveInit(symbols);
            } else {
                saveInit(symbols);
            }
        } else {
            String[] symbolsArrays = symbols.split(",");
            for (String symbol : symbolsArrays) {
                threadPoolComponent.getExecutor().submit(() -> {
                    logger.info("当前开始初始化币对单个k线图: {}", symbol);
                    Item bySymbol = itemService.findBySymbol(symbol);
                    if (Item.cryptos.equalsIgnoreCase(bySymbol.getType())) {
                        cryptosKlineService.saveInit(symbol);
                    } else if ("1".equalsIgnoreCase(bySymbol.getFake())) {
                        fakeKlineInitService.saveInit(symbols);
                    } else {
                        saveInit(symbol);
                    }
                    logger.info("当前开始初始化完成币对k线图: {}", symbol);
                });

            }

        }
    }


    private final void saveInit(String symbol) {
        Item bySymbol = itemService.findBySymbol(symbol);
        // 机器人的价格，无需初始化
        if ("1".equalsIgnoreCase(bySymbol.getFake())) {
            return;
        }
        Map<String, List<Kline>> dailyWeekMonthHistoryMap = hobiDataService.getDailyWeekMonthHistory(symbol);
        Map<String, List<Kline>> hourlyAndMinuteHistoryMap = hobiDataService.getHourlyAndMinuteHistory(symbol);
        klineService.saveInit(symbol, dailyWeekMonthHistoryMap, hourlyAndMinuteHistoryMap);
    }

}
